package com.lu.pojo.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author luzhenfang
 * @date 2020 05 28
 * @description 分析效率
 */
public class TestAnalyzePower {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        test01();
        test02();
        test03();
    }
    public static void test01(){
        // 普通方式
        User user = new User("张三",1,20);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通方式操作对象10亿次 "+(endTime-startTime)+" ms");
        // 关闭检查
    }
    public static void test02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        // 反射方式
        Class<?> aClass = Class.forName("com.lu.pojo.reflection.Cat");
        Cat o = (Cat) aClass.newInstance();
        System.out.println(o);
        Method getName = aClass.getMethod("getAge");
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(o,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式操作对象10亿次 "+(endTime-startTime)+" ms");

    }

    public static void test03() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        // 反射方式
        Class<?> aClass = Class.forName("com.lu.pojo.reflection.Cat");
        Cat o = (Cat) aClass.newInstance();
        System.out.println(o);
        Method getAge = aClass.getMethod("getAge");
        long startTime = System.currentTimeMillis();
        // 关闭安全检测
        getAge.setAccessible(true);
        for (int i = 0; i < 1000000000; i++) {
            getAge.invoke(o,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("(关闭安全检测)反射方式操作对象10亿次 "+(endTime-startTime)+" ms");

    }
}
